package com.retry.task.admin.base.datasource;

import com.alibaba.druid.util.StringUtils;
import com.retry.task.datasource.annotation.MultiMapperScan;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @Author: gao.gwq@alibaba-inc.com
 * @Date: 2020/3/24 3:20 下午
 * @Version: 1.0
 * @Description: TODO
 */
@Configuration
@MultiMapperScan(basePackages = "com.retry.task")
public class RetryTddlMyBatisConfigurer {

    @Autowired
    private Environment environment;

    @Bean("retryTaskSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("retryTaskDataSource") DataSource tddlDataSource)
            throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(tddlDataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource resource = resolver.getResource(environment.getProperty("mybatis.retry.task.config-location"));
        factory.setConfigLocation(resource);
        factory.setVfs(SpringBootVFS.class);
        String mapperLocations = environment.getProperty("mybatis.mapper-locations");
        if (!StringUtils.isEmpty(mapperLocations)) {
            Resource[] resourcesArr = resolver.getResources(mapperLocations);
            factory.setMapperLocations(resourcesArr);
        }
        return factory.getObject();
    }

}